<template>
  <ContentWrap :loading="loading">
    <div class="flex-c mb-24">
      <h2>费用支付申请</h2>
    </div>
    <div class="px-32">
      <el-form 
        ref="formRef" 
        :inline="true" 
        :model="formData.data" 
        :rules="formRules" 
        class="-mb-15px"
        label-width="auto"
      >
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectName">
              <div class="flex-s" style="width: 100%">
                <div class="coord flex-s formInp mr-12">
                  <span v-if="formData.data.projectName">{{ formData.data.projectName }}</span>
                  <span v-else style="color: rgb(159 155 155);">请选择项目</span>
                </div>
                <el-button type="primary" :disabled="disabledFrom" @click="addProject">选择项目</el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目编号">
              <el-input
                class="formInp" 
                disabled
                v-model="formData.data.projectCode"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联主合同">
              <el-input
                class="formInp" 
                disabled
                v-model="formData.data.mainContract"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="主合同编号">
              <el-input
                class="formInp" 
                disabled
                v-model="formData.data.mainContractCode"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="flex-c mt-24">
      <el-button class="!w-100px" :disabled="disabledFrom" type="primary" @click="addExpend">添加明细</el-button>
    </div>

    <div class="expendContainer" v-for="(item, index) in formData.data.expenseDetails" :key="index">
      <el-row :gutter="16">
        <el-col :span="24">
          <el-form-item :label="`明细${index + 1}`">
            <div class="flex-s mb-12" v-if="formData.data.expenseDetails.length > 1"><el-button type="danger" :disabled="disabledFrom" @click="delExpend(index)">删除明细</el-button></div>
            <div class="content_main">
              <div class="main_title flex-b">
                费用明细
                <div class="mony">可支含税金额：<span>¥ {{ item.availableFund ? item.availableFund /100 : '0.00' }}</span></div>
                <div class="mony">累计已支含税金额：<span>¥ {{ item.accumulatedFund ? item.accumulatedFund /100 : '0.00' }}</span></div>
                <div class="mony">剩余可支含税金额：<span>¥ {{ item.remainingFund ? item.remainingFund /100 : '0.00' }}</span></div>
              </div>
            </div>
            <el-table :data="item.expendTypeList">
              <el-table-column align="center" prop="subContractId">
                <template #header>
                  <div class="flex-c">
                    <span class="mr-4">费用类型</span>
                    <el-tooltip
                      class="box-item"
                      effect="dark"
                      content="选择项目后，才能选择费用类型"
                      placement="top-start"
                    >
                      <el-icon><QuestionFilled /></el-icon>
                    </el-tooltip>
                  </div>
                </template>
                <template #default="scope">
                  <el-select v-model="scope.row.expenseType" :disabled="disabledFrom" placeholder="请选择费用类型" @change="e => changeExpenseType(e, index)">
                    <el-option v-for="item in childContractList" :key="item.id" :label="item.expenseType" :value="item.expenseType" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column align="center" label="本次申报金额（含税）" prop="declaredAmountTax">
                <template #default="scope">
                  <el-input-number 
                    class="formInp"
                    controls-position="right" 
                    :disabled="disabledFrom"
                    :min="0" 
                    v-model="scope.row.declaredAmountTax" 
                    placeholder="请输入本次申报金额（含税）"
                    @input="e => declaredChange(e, index)"
                  />
                </template>
              </el-table-column>
              <el-table-column align="center" label="税率" prop="taxRate">
                <template #default="scope">
                  <div class="flex-s">
                    <el-input-number 
                      class="formInp mr-6"
                      :disabled="disabledFrom"
                      controls-position="right" 
                      :min="0" 
                      :max="100"
                      v-model="scope.row.taxRate" 
                      placeholder="请输入税率"
                      @input="e => taxRateChange(e, index)"
                    />%
                  </div>
                </template>
              </el-table-column>
              <el-table-column align="center" label="本次申报金额（不含税）" prop="declaredAmountNoTax">
                <template #default="scope">
                  <el-input-number 
                    class="formInp"
                    controls-position="right" 
                    :min="0" 
                    disabled
                    v-model="scope.row.declaredAmountNoTax" 
                    placeholder="" 
                  />
                </template>
              </el-table-column>
              <el-table-column align="center" label="收款单位" prop="companyName">
                <template #default="scope">
                  <div class="flex-c" v-if="scope.row.companyName">
                    {{ scope.row.companyName }}
                    <el-button class="ml-12" type="primary" :disabled="disabledFrom" @click="checkCompany(index, scope.row.expenseType)">修改单位</el-button>
                  </div>
                  <el-button type="primary" v-else :disabled="disabledFrom" @click="checkCompany(index, scope.row.expenseType)">选择单位</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="备注">
            <el-input
              v-model="item.remarks"
              :disabled="disabledFrom"
              type="textarea"
              :autosize="{ minRows: 8}"
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="上传附件">
            <div class="upload_box" style="width: 100%;">
              <UploadFile
                v-model="item.attachments"
                :disabled="disabledFrom"
                class="upload-demo"
                :http-request="e => customRequest(e, index)"
                :fileSize="20"
                :fileType="['jpg', 'png', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt']"
                :limit="10"
              />
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </div>
  </ContentWrap>
  <ContentWrap class="flex-c" v-if="disabledFrom">
    <el-button class="!w-80px" type="warning" @click="closeForm">返回</el-button>
  </ContentWrap>
  <ContentWrap class="flex-c" v-else>
    <el-button class="!w-80px" type="primary" :loading="loading" @click="submitForm(1)">保存</el-button>
    <el-button class="!w-80px" type="primary" :loading="loading" @click="submitForm(2)">提交</el-button>
    <el-button class="!w-80px" type="warning" @click="closeForm">取消</el-button>
  </ContentWrap>

  <ProjectDialog ref="relationsDialogRef" @change="relationsChange" />
  <CompanyDialog ref="companyDialogRef" @change="companyChange" />
</template>
<script setup>
  import {ref,reactive} from "vue"
  import { QuestionFilled } from '@element-plus/icons-vue'
  import ProjectDialog from './projectDialog.vue'
  import CompanyDialog from './companyDialog.vue'
  import * as ExpenditureApi from '@/api/viewsApi/expenditure'
  import * as ProjectApi from '@/api/viewsApi/project'
  import { UploadFile } from "@/components/UploadFile/index.ts"
  import { updateFile } from "@/api/infra/file/index.ts"
  import { ElMessage, ElMessageBox } from 'element-plus'
  const { t } = useI18n()
  const relationsDialogRef = ref()
  const companyDialogRef = ref()
  const formRef = ref(null)
  const childContractList = ref([])
  const message = useMessage() // 消息弹窗
  let loading = ref(false)
  const goBack = inject('goBack', () => {})
  let disabledFrom = ref(false)
  const formData = reactive({
    data: {
      projectName: '', // 项目名称
      projectCode: '', // 项目编号
      mainContract: '', // 关联主合同
      mainContractCode: '', // 主合同编号

      expenseDetails: [// 费用明细
        { 
          availableFund: null, // 可支含税金额
          accumulatedFund: null, // 累计已支含税金额
          remainingFund: null, // 剩余可支含税金额
          attachments: [], // 附件
          remarks: '', // 备注
          expendTypeList: [
            {
              subContractId: null, // 费用类型 - 子合同Id
              expenseType: '', // 费用类型 - 名称
              declaredAmountTax: null, // 本次申报金额(含税)
              taxRate: '', // 税率
              declaredAmountNoTax: null, // 本次申报金额(不含税)
              companyName: '', // 选中的收款单位名称
              companyId: null, // 选中的收款单位Id
            },
          ], // 费用类型列表
        }
      ],
    }
  })
  const formRules = {
    projectName: [{ required: true, validator: notEmpty, msg: '请选择项目', trigger: 'blur' }],
  }
  // 校验不能为空
  function notEmpty(rule, value, callback) {
    if (!value) {
      return callback(new Error(rule.msg))
    }
  }

  const init = async (id) => {
    if (id) {
      loading.value = true
      try {
        const data = await ExpenditureApi.getExpenseDetail(id)
        if(data.expenseDetails && data.expenseDetails.length > 0){
          data.expenseDetails = data.expenseDetails.map(item => {
            return {
              attachments: item.attachments, // 附件
              remarks: item.remarks, // 备注
              id: item.id,
              availableFund: item.availableFund, // 可支含税金额
              accumulatedFund: item.accumulatedFund, // 累计已支含税金额
              remainingFund: item.remainingFund, // 剩余可支含税金额
              expendTypeList: [
                {
                  dataType: item.dataType,
                  subContractId: item.subContractId, // 费用类型 - 子合同Id
                  expenseType: item.expenseType, // 费用类型 - 名称
                  declaredAmountTax: item.declaredAmountTax / 100, // 本次申报金额(含税)
                  taxRate: item.taxRate, // 税率
                  declaredAmountNoTax: item.declaredAmountNoTax / 100, // 本次申报金额(不含税)
                  companyName: item.companyName, // 选中的收款单位名称
                  companyId: item.companyId, // 选中的收款单位Id
                },
              ],
            }
          })
        }
        if(data.projectId){
          getChildContract(data.projectId)
        }
        disabledFrom.value = data.applyStatus !== 1
        formData.data = data
        console.log(formData.data, disabledFrom.value, '拼接的数据。。。');
        
      } finally {
        loading.value = false
      }
    }
  }  
  /**获取项目下的子合同列表 */
  const getChildContract = async (id) => {
    const data = await ProjectApi.getProjectChildContract(id)
    
    childContractList.value = data.map(item => {
      return {
        subContractId: item.id,
        expenseType: item.name,
        dataType: 1,
      }
    })

    let concatData = [
      ...childContractList.value,
      {
        subContractId: null,
        expenseType: '管理成本',
        dataType: 2,
      },
      {
        subContractId: null,
        expenseType: '其他成本',
        dataType: 3,
      },
    ]
    concatData.forEach((item, index) => item.id = index + 1)
    childContractList.value = concatData
    
  }
  // 获取费用明细
  const getExpendDetaile = async (projectId, contractId, dataType, index) => {
    let parms = {
      projectId,
      contractId,
      dataType,
    }
    const data = await ExpenditureApi.getExpenditureDetail(parms)
    let tableItem = formData.data.expenseDetails[index]
    tableItem.availableFund = data.availableFund
    tableItem.accumulatedFund = data.accumulatedFund
    tableItem.remainingFund = data.remainingFund
  }
  /** 选择项目逻辑处理 - 开始 */
  const addProject = () => {
    relationsDialogRef.value.init()
  }
  const relationsChange = (data) => {
    const {id, name, code, contractName, contractNumber} = data
    formData.data.projectId = id
    formData.data.projectName = name
    formData.data.projectCode = code
    formData.data.mainContract = contractName
    formData.data.mainContractCode = contractNumber
    getChildContract(id)
  }
  const relationsDel = async (index) => {
    try {
      // 删除的二次确认
      await message.delConfirm(`是否删除“明细${index+1}”？`)
      formData.data.projectSubcontractList.splice(index, 1)
    } catch {}
  }
  /** 选择项目逻辑处理 - 结束 */
  
  /**
   * 明细列表逻辑处理 - 开始
   */

  // 费用类型改变
  const changeExpenseType = (e, index) => {
    let tableItem = formData.data.expenseDetails[index].expendTypeList[0]
    tableItem.expenseType = e
    childContractList.value.forEach(item => {
      if(item.expenseType === e){
        tableItem.dataType = item.dataType
        tableItem.subContractId = item.subContractId
      }
    })
    getExpendDetaile(formData.data.projectId, tableItem.subContractId, tableItem.dataType, index)
  }

  // 添加费用明细
  const addExpend = () => {
    if(formData.data.expenseDetails.length > 10){
      ElMessage.error('最多添加10条明细')
      return
    }
    formData.data.expenseDetails.push({
      availableFund: '0.00', // 可支含税金额
      accumulatedFund: '0.00', // 累计已支含税金额
      remainingFund: '0.00', // 剩余可支含税金额
      expendTypeList: [
        {
          subContractId: null, // 费用类型 - 子合同Id
          expenseType: '', // 费用类型 - 名称
          declaredAmountTax: null, // 本次申报金额(含税)
          taxRate: '', // 税率
          declaredAmountNoTax: null, // 本次申报金额(不含税)
          companyName: '', // 选中的收款单位名称
          companyId: null, // 选中的收款单位Id
        },
      ], // 费用类型列表
      attachments: [], // 附件
      remarks: '', // 备注
    })
  }
  // 删除费用明细
  const delExpend = async (index) => {
    if(formData.data.expenseDetails.length === 1){
      ElMessage.error('至少保留一条明细')
      return
    }
    try {
      // 删除的二次确认
      await ElMessageBox.confirm(`是否删除“明细${index+1}”数据？`,'是否删除？',
              {
                confirmButtonText: t('common.ok'),
                cancelButtonText: t('common.cancel'),
                type: 'warning'
              }
            )
      formData.data.expenseDetails.splice(index, 1)
    } catch {}
  }
  // 选择收款单位
  const checkCompany = (index, name) => {
    if(!name){
      ElMessage.error(`请选择“明细${index+1}”的费用类型`)
      return
    }
    companyDialogRef.value.init(index)
  }
  // 选择收款单位
  const companyChange = (row, index) => {
    let tableItem = formData.data.expenseDetails[index].expendTypeList[0]
    tableItem.companyName = row.name
    tableItem.companyId = row.id
  }
  const customRequest = async (options, index) => {
    const upFilesData = new FormData()
    upFilesData.append('file', options.file)
    try {
      const res = await updateFile(upFilesData)
      formData.data.expenseDetails[index].attachments.push(res.data)
    }finally {
      
    }
  }
  const declaredChange = (e, index) => {
    let tableItem = formData.data.expenseDetails[index].expendTypeList[0]
    tableItem.declaredAmountTax = e
    let taxRate = tableItem.taxRate
    setTimeout(() => {
      tableItem.declaredAmountNoTax = (e - (e * (taxRate / 100))).toFixed(2)
    },500)
  }
  // 税率改变
  const taxRateChange = (e, index) => {
    let tableItem = formData.data.expenseDetails[index].expendTypeList[0]
    tableItem.taxRate = e
    let declaredAmountTax = tableItem.declaredAmountTax
    setTimeout(() => {
      tableItem.declaredAmountNoTax = (declaredAmountTax - (declaredAmountTax * (e / 100))).toFixed(2)
    },500)
  }
  /**
   * 明细列表逻辑处理 - 结束
   */

  const submitForm = async (type) => {
    const formEl = formRef.value
    if (!formEl) return
    let status = true
    formEl.validate((valid) => status = valid)
    setTimeout(()=> {
      const {projectId} = formData.data
      if(!projectId){
        ElMessage.error('请选择项目')
      }
      if (!status) return
      
      let parmsData = JSON.parse(JSON.stringify(formData.data))
      parmsData.applyStatus = type
      parmsData.expenseDetails = parmsData.expenseDetails.map(item => {
        return {
          status: type,
          attachments: item.attachments,
          projectId: parmsData.projectId,
          remarks: item.remarks,
          ...item.expendTypeList[0],
        }
      })
      parmsData.expenseDetails.forEach(item => {
        item.declaredAmountTax = item.declaredAmountTax * 100
        item.declaredAmountNoTax = item.declaredAmountNoTax * 100
      })

      let hintTxt = ''
      let isSubmit = false
      for(let i = 0; i < parmsData.expenseDetails.length; i++){
        if(!parmsData.expenseDetails[i].expenseType){
          hintTxt = `请选择“明细${i+1}”的费用类型`
          isSubmit = true
          break
        }
        if(!parmsData.expenseDetails[i].declaredAmountTax){
          hintTxt = `请输入“明细${i+1}”的本次申报金额(含税)`
          isSubmit = true
          break
        }
        if(!parmsData.expenseDetails[i].taxRate){
          hintTxt = `请输入“明细${i+1}”的税率`
          isSubmit = true
          break
        }
        if(!parmsData.expenseDetails[i].companyId){
          hintTxt = `请选择“明细${i+1}”的收款单位`
          isSubmit = true
          break
        }
      }
      if(isSubmit){
        ElMessage.error(hintTxt)
        return
      }

      if (!parmsData.id) {
        ExpenditureApi.addExpense(parmsData).then(res => {
          goBack()
          ElMessage.success(type === 1 ? '保存成功' :'新增成功')
        })
      } else {
        ExpenditureApi.editExpense(parmsData).then(res => {
          goBack()
          ElMessage.success(type === 1 ? '保存成功' :'编辑成功')
        })
      }
    },10)
  }
  const closeForm = () => {
    // 关闭表单弹窗逻辑
    goBack()
  }


  defineExpose({init})
</script>
<style lang="scss" scoped>
.coord{
  height: 32px;
  box-sizing: border-box;
  padding: 4px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: not-allowed;
  color: #636660;
}
::v-deep .el-form-item{
  width: 100%;
}
.formInp{
  width: 100%;
}
.mt-32{
  font-size: 14px;
}
.expendContainer{
  width: 100%;
  margin-top: 24px;
  padding: 24px 24px 0px 24px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  background: #eff7ff;
}
.content_main {
    padding: 6px 12px;
    width: 100%;
    background: #e6e4e4;
    border-radius: 6px;
    .main_title {
        font-family: PingFang SC, PingFang SC;
        font-weight: 600;
        font-size: 14px;
        color: #1D1D1D;
    }
}
::v-deep .el-input-number .el-input__inner {
  text-align: left;
}
.upload_box{
  flex-direction: column;
  .uploader__text{
    margin-top: 6px;
  }
}
::v-deep .el-upload-list{
  overflow-y: scroll;
  height: 120px;
}
</style>
